package com.rectcircle.scalatrateset.model

import org.squeryl.KeyedEntity
import org.squeryl.PrimitiveTypeMode._
import java.sql.Timestamp

import org.squeryl.annotations.Column
import java.util.Date

import org.squeryl.dsl.CompositeKey2

//模型类，尽量减少入侵

class LibraryDbObject extends KeyedEntity[Long] {
	val id:Long = 0
}

case class Author ( firstName: String,
			   lastName: String,
			   email: Option[String]) extends LibraryDbObject {
	def this() = this("", "", Some(""))
	
	//this 是一的一方 所以 一对多
	//lazy val books:OneToMany[Book] = LibraryDbSchema.authorToBooks.left(this)
	var books:Vector[Book] = _
}

case class Book(title: String,
		   @Column("AUTHOR_ID")authorId: Long,
			coAuthorId: Option[Long]) extends LibraryDbObject {
	def this() = this("", 0, Some(0L))
	
	//此框架具有侵入性，可以手动指定，在Db层实现
	//this 是多的一方 所以是多对一
	//lazy val author:ManyToOne[Author] = LibraryDbSchema.authorToBooks.right(this)
	var author:Author = _
	//多对多
	//lazy val readers:ManyToMany[Reader, Borrowal] = LibraryDbSchema.borrowals.right(this)
	var readers:Vector[(Reader,Borrowal)] = _
}

////手动管理多对多关系
//case class Borrowal(bookId: Long,
//			    readerId: Long,
//			    scheduledToReturnOn: Date,
//			    returnedOn: Option[Timestamp],
//			    numberOfPhonecallsForNonReturn: Int) extends LibraryDbObject

//多对多映射管理
case class Borrowal(bookId: Long,
			    readerId: Long,
			    scheduledToReturnOn: Date,
			    returnedOn: Option[Timestamp],
			    numberOfPhonecallsForNonReturn: Int) extends  KeyedEntity[CompositeKey2[Long,Long]]{
	def id = compositeKey(bookId, readerId)
}

case class Reader( username:String,
			  password:String,
			  maxBorrowBooksCount:Int
			) extends LibraryDbObject {
	def this() = this("","",15)
	
	////侵入式写法
	//lazy val books:ManyToMany[Book,Borrowal] = LibraryDbSchema.borrowals.left(this)
	//非侵入式写法，将逻辑在Db层手写
	var books:Vector[(Book,Borrowal)] = _
	
}

